<template>
	<div>
		<div style="width: 100%;height: 10vh;">
			<div style="height: 30px;width: 100%;">
				<div style="display: flex;justify-content:space-between;">
					<Row type="flex" justify="start" class="code-row-bg" style="float: left;padding-right: 5px; height: 40px;line-height: 60px;">
						<div style="float:left; margin-left:10px; line-height: 40px;">
							<Button size="small" icon="ios-cloud-upload" @click="UploadDetails = true">上传</Button>
							<Drawer title="文件上传" :closable="false" v-model="UploadDetails">
								<Upload multiple type="drag" action="//jsonplaceholder.typicode.com/posts/" :before-upload="UploadFile">
									<div style="padding: 20px 0">
										<Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
										<p>Click or drag files here to upload</p>
									</div>
								</Upload>
							</Drawer>
							<Button size="small" icon="ios-add-circle" @click="NewFolder = true">新建</Button>
							<Modal title="新建文件夹" v-model="NewFolder" @on-ok="YesFolder" @on-cancel="Nofolder">
								<Input v-model="FolderValue" placeholder="请输入新建文件夹的名称……" style="width: 100%;" />
							</Modal>
						</div>
						<div style="margin-left:5px; line-height: 40px;">
							<Button size="small" v-show="!Copy" icon="md-trash" @click="handleContextMenuCopy">粘贴</Button>
							<ButtonGroup>
								<Button size="small" v-show="button" icon="md-trash" @click="Deletes">删除</Button>
								<Button size="small" v-show="button" icon="md-cloud-download" @click="download">下载</Button>
								<Button size="small" v-show="button" icon="ios-copy" @click="Copys">复制到</Button>
								<Button size="small" v-show="button" icon="ios-albums">移动到</Button>
							</ButtonGroup>
						</div>
					</Row>

					<div style="display: flex;align-items: center;">
						<div style="height: 40px;">
							<i-switch size="small" v-model="switch1" @on-change="change" style="margin-top: 12px;float: right;margin-right: 10px;" />
							<Input v-model="SearchValue" suffix="ios-search" size="small" placeholder="搜索" style="margin-top: 7px; width: auto; float: right; margin-right: 10px;"
							 @on-change="sousuo" />
						</div>
					</div>
				</div>
			</div>
			<div style="width: 100%;height: 30px;background: #000099;">
				<div style="height: 50px; background-color: #FFFFFF;">
					<Row type="flex" justify="start" class="code-row-bg" style="float: left; ">
						<div style="height: 50px; line-height: 50px; margin-left: 10px;">
							<a style="color: #3f3f3f;" @click="Back">
								<Icon type="ios-arrow-back" size="20" />
							</a>
							<!-- 返回上一层 -->
							<a style="margin-left: 5px;" @click="Refresh">
								<Icon type="md-refresh" color="#3f3f3f" size="20" />
							</a>

							<Divider type="vertical" size="default" />
						</div>
						<Breadcrumb>
							<a style="height: 50px; line-height: 50px;color: #3f3f3f;" @click="Breadcrumb(index)" v-for="(item,index) in path">
								<BreadcrumbItem>
									<Icon type="ios-home-outline"></Icon>
									{{item}}
								</BreadcrumbItem>
							</a>
						</Breadcrumb>
					</Row>
				</div>
			</div>
		</div>
		<div></div>
		<div style="width: 100%;height: 76vh;overflow:auto;">
			<Table size="small" :columns="columns1" :data="list" v-if="!switch1" @on-selection-change="select" @on-row-dblclick="dbClick"
			 show-context-menu @on-contextmenu="handleContextMenu">
				<template slot="contextMenu">
					<DropdownItem @click.native="handleContextMenuDownload">下载</DropdownItem>
					<DropdownItem @click.native="NewFile = true">重命名</DropdownItem>
					<Modal title="重命名" v-model="NewFile" @on-ok="YesFile" @on-cancel="NoFile">
						<Input v-model="FileValue" placeholder="请输入重命名的名称……" style="width: 100%;" />
					</Modal>
					<DropdownItem @click.native="handleContextMenuCopy" v-if="Copy == true">复制</DropdownItem>
					<DropdownItem @click.native="handleContextMenuCopy" v-else>粘贴</DropdownItem>
					<DropdownItem @click.native="handleContextMenuDelete" style="color: #ed4014">删除</DropdownItem>
				</template>
			</Table>
			<div v-if="switch1" style="width: 100%;">
				<ul v-for="item in list" style="float: left;margin: 5px;">
					<div id="div" @dblclick="dbClick(item)" >
						<img :src="'src/renderer/assets/icon/'+ item.category + '.png'" width="60px" height="60px" />
						<h5>{{item.server_filename}}</h5>
					</div>
				</ul>
			</div>
		</div>
	</div>

	</div>
</template>

<script>
	import axios from "axios";
	import qs from "qs";
	export default {
		data() {
			return {
				list: [], //文件列表
				button: false, //多选显示按钮
				value: "", //新建文件夹的value
				switch1: false, //切换缩略图
				SearchValue: "", //搜索文件value
				Selection: [], //多选按钮事件
				NewFolder: false, //新建文件夹弹窗
				FolderValue: "", //新建文件夹value
				NewFile: false, //重命名弹窗
				FileValue: "", //重命名value
				path: [], //面包屑路径
				ContextMenu: [],
				fsid: [], //fs_id获取下载链接
				download_url: [], //下载链接
				UploadDetails: false, //上传信息查看
				Uploadfiles: [],
				Copy: true, //复制、粘贴文件判断
				CopyFile: [],
				admin: [],
				columns1: [{
						type: "selection",
						width: 60,
						align: "center"
					},
					{
						title: "文件名",
						key: "server_filename"
					},
					{
						title: "最后修改时间",
						key: "local_mtime",
						width: 300,
						align: "center"
					},
					{
						title: "文件大小",
						key: "size",
						width: 150,
						align: "center"
					}
				]
			};
		},
		mounted() {
			//获取文件列表
			this.Refresh();
			console.log('123')
			var access_token = window.sessionStorage.getItem('access_token')
			axios({
				url:'https://pan.baidu.com/api/quota?access_token=' + access_token,
				method:'get'
			}).then((res)=>{
				console.log(res.data)
				window.sessionStorage.setItem('Baidu_total',res.data.total)
				window.sessionStorage.setItem('Baidu_used',res.data.used)
			})
		},
		methods: {
			Breadcrumb(row, index) {
				// 获取点击的名字
				var name = this.path[row];
				// 将数组转换字符串
				var Clickpath = this.path.join("/");
				// 截取到点击的路径
				var path = Clickpath.substring(
					0,
					Clickpath.lastIndexOf(name) + name.length
				);
				// 将路径转换成数组
				this.path = path.split("/");
				this.Refresh();
			},
			//刷新文件列表
			Refresh() {
				var access_token = window.sessionStorage.getItem("access_token");
				var path = "/" + this.path.join("/");
				axios({
					url: "https://pan.baidu.com/rest/2.0/xpan/file?method=list&access_token=" +
						access_token +
						"&dir=/" +
						path +
						"&start=0&limit=10000&web=web",
					method: "get"
				}).then(respanse => {
					this.list = respanse.data.list;
					if (this.list.length != 0) {
						for (var i = 0; i < this.list.length; i++) {
							//定义空字符串size
							var size = "";
							//获取数组内的size并赋值变量
							var fileSize = this.list[i].size;
							//判断文件大小
							if (fileSize < 1024) {
								size = fileSize + "B";
							} else if (fileSize < 1048576) {
								size = (fileSize / 1024).toFixed(1) + "K";
							} else if (fileSize < 1073741824) {
								size = (fileSize / 1048576).toFixed(1) + "M";
							} else {
								size = (fileSize / 1073741824).toFixed(1) + "G";
							}
							// 将数据重新放入到obj数组里面
							var obj = this.list[i]; //或者 var obj=new Object();
							var key = "size";
							obj[key] = size;

							// 获取文件时间戳
							var time = this.list[i].local_mtime;
							// 时间戳换算
							var timestamp4 = new Date(time * 1000);
							//拼接日期
							var FileTime =
								timestamp4.toLocaleDateString().replace(/\//g, "-") +
								" " +
								timestamp4.toTimeString().substr(0, 8);

							var key = "local_mtime";
							obj[key] = FileTime;
						}
					} else {}
				});
			},
			//批量操作
			select(Selection) {
				//对选中的数据 显示按钮，执行操作

				//将选中的数据，存储到数组里面，以便使用
				this.Selection = Selection;

				if (Selection.length != 0) {
					this.button = true;
				} else {
					this.button = false;
				}
			},
			//缩略图
			selectaaa(row){
			},
			//缩略图切换
			change(status) {
				this.$Message.info("开关状态：" + status);
			},
			//搜索文件
			sousuo() {
				var access_token = window.sessionStorage.getItem("access_token");
				if (this.SearchValue != "") {
					const name = this.SearchValue;
					axios({
						url: "https://pan.baidu.com/rest/2.0/xpan/file?method=search&access_token=" +
							access_token +
							"&key=" +
							name,
						method: "get"
					}).then(res => {
						this.list = res.data.list;
					});
				} else {
					this.Refresh();
				}
			},
			//tab表格双击事件
			dbClick(row) {
				if (row.category == 3) {
					this.$Modal.info({
						title: row.server_filename,
						content: '<img src="'+ row.thumbs.url3+'" width="100%" height="100%"  />'
					});
				}
				if (row.isdir == 1) {
					//更改面包屑
					this.path.splice(this.path.length, 0, row.server_filename);
					//进入子目录
					this.Refresh();
				} else {
					console.log(row)
					this.$Message.info("该文件类型暂时不支持在线预览！");
					window.open('https://netdisk-pan.baidupcs.com/disk/docview?bdstoken=40cc3685c9145c982305012df4d4ac0b&uk=1100973129639&path=%2F%E3%80%8A%E9%85%B7%E7%8C%AB%E4%BA%91%E7%9B%98%E7%AE%A1%E7%90%86%E5%99%A8%E3%80%8B%E9%A1%B9%E7%9B%AE-%E7%94%A8%E6%88%B7%E6%89%8B%E5%86%8C.docx&share=0')
				}
			},
			//确定新建文件夹
			YesFolder() {
			
				var value = this.FolderValue;
				var access_token = window.sessionStorage.getItem("access_token");
				var path = "/" + this.path.join("/");
				path = path + "/" + value;
				axios({
					url: "https://pan.baidu.com/rest/2.0/xpan/file?method=create&access_token=" +
						access_token,
					method: "post",
					data: qs.stringify({
						path: path,
						isdir: 1
					})
				}).then(res => {
					this.$Message.success("新建文件夹：" + value);
					this.Refresh();
				});
			},
			//取消新建文件夹
			Nofolder() {
				this.$Message.warning("已取消新建文件夹！");
			},
			//批量删除
			Deletes() {
				this.$Modal.confirm({
					title: "温馨提示",
					content: "<p>是否需要删除该文件？</p>",
					onOk: () => {
						var Selection = this.Selection;
						for (var i = 0; i < Selection.length; i++) {
							var access_token = window.sessionStorage.getItem("access_token");
							axios({
								url: "https://pan.baidu.com/rest/2.0/xpan/file?method=filemanager&access_token=" +
									access_token +
									"&opera=delete",
								method: "post",
								// data: {
								// 	async: '1',
								// },
								data: qs.stringify({
									async: "1",
									filelist: '["' + Selection[i].path + '"]'
								})
							}).then(res => {
								this.Refresh();
								this.button = false;
							});
						}
						this.$Message.info("Clicked ok");
					},
					onCancel: () => {
						this.$Message.info("Clicked cancel");
					}
				});
			},
			// 批量复制粘贴
			Copys() {
				var Selection = this.Selection;
				console.log(Selection);
				for (var i = 0; i < Selection.length; i++) {
					var path = "/" + this.path.join("/");
					var access_token = window.sessionStorage.getItem("access_token");
					var name = Selection[i].server_filename;
					axios({
						url: "https://pan.baidu.com/rest/2.0/xpan/file?method=filemanager&access_token=" +
							access_token +
							"&opera=copy",
						method: "post",
						data: qs.stringify({
							async: 2,
							filelist: '[{"path":"/' +
								name +
								'","dest":"/1","newname":"' +
								name +
								'","ondup":"overwrite"}]'
						})
					}).then(res => {
						console.log(res);
						this.$Message.success(
							"粘贴文件：" + this.CopyFile.server_filename + "成功！"
						);
						// 刷新页面
						this.Refresh();
					});
				}
			},
			// 返回上一层
			Back() {
				//判断是否为根目录
				if (this.path.length == 0) {
					this.$router.push("/Netdisc");
				}
				//当前目录-1
				this.path.splice(-1, 1);
				//刷新目录
				this.Refresh();
			},
			// 右键点击事件
			handleContextMenu(row) {
				this.ContextMenu = row;
				this.FileValue = row.server_filename;
			},
			// 确定重命名
			YesFile() {
				var value = this.FileValue;
				var access_token = window.sessionStorage.getItem("access_token");
				var path = this.ContextMenu.path;

				axios({
					url: "https://pan.baidu.com/rest/2.0/xpan/file?method=filemanager&opera=rename&access_token=" +
						access_token,
					method: "post",
					data: qs.stringify({
						async: "2",
						filelist: '[{"path":"' + path + '","newname":"' + value + '"}]'
					})
				}).then(res => {
					this.$Message.success("重命名：" + value);
					var _this = this;
					setTimeout(function() {
						_this.Refresh();
					}, 500);
				});
			},
			// 取消重命名
			NoFile() {
				this.$Message.warning("已取消重命名！");
			},
			// 上传文件
			UploadFile(files) {
				console.log(files);
				//第一步 预上传
				var _this = this;
				var access_token = window.sessionStorage.getItem("access_token");
				axios({
					url: "https://pan.baidu.com/rest/2.0/xpan/file?method=precreate&access_token=" +
						access_token,
					method: "post",
					data: qs.stringify({
						path: "/" + files.name,
						autoinit: 1,
						target_path: "/",
						block_list: '[""]'
					})
				}).then(res => {
					console.log(res.data);
					var uploadid = res.data.uploadid;
					//第二步分片上传

					// 读取完成时的回调
					let formData = new FormData();
					formData.append("file", files);
					var BDUSS =
						"E5DbGVrYmpyMEN-TXVqdUYzTlBkRE1JOFNaTGhCWGxybWlVWXo2SU5wdVFnVkpmSVFBQUFBJCQAAAAAAQAAAAEAAADxV3gYv-HDqM34xcwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJD0Kl-Q9CpfW";
					axios({
						url: "https://d.pcs.baidu.com/rest/2.0/pcs/superfile2?method=upload&BDUSS=" +
							BDUSS +
							"&app_id=250528&method=upload&type=tmpfile&path=/" +
							files.name +
							"&uploadid=" +
							uploadid +
							"&partseq=0",
						method: "post",
						data: formData
					}).then(res => {
						console.log(res);

						// 第三步上传成功
						axios({
							url: "https://pan.baidu.com/rest/2.0/xpan/file?method=create&access_token=" +
								access_token,
							method: "post",
							data: qs.stringify({
								path: "/" + files.name,
								size: files.size,
								uploadid: uploadid,
								target_path: "/",
								block_list: '["' + res.data.md5 + '"]'
							})
						}).then((res, req) => {
							console.log(res.data);
							console.log(res);
							_this.Refresh();
						});
					});
				});
			},
			// 获取上传进度条
			sadfasdf(event, file, fileList) {
				console.log(file.percentage);
				console.log(file.name);
				// 打开上传详细
				this.UploadDetails = true;
				// 把详细资料添加到数组
				this.Uploadfiles = file;
				// 上传成功 Buuton不展开
				this.button = false;
				// 成功提示
				if (file.percentage == 100) {
					this.$Message.success("上传" + file.name + "成功");
				}
			},
			// 批量下载文件
			download() {
				var access_token = window.sessionStorage.getItem("access_token");
				// 获取选中的文件
				var Selection = this.Selection;
				// 把fsid 放在一个数组里面
				for (var i = 0; i < Selection.length; i++) {
					console.log(i);
					this.fsid.splice(this.fsid.length, 0, Selection[i].fs_id);
				}
				// 把fsid数组里面的数据拆分成一个字符串并用,号分开
				var Clickpath = this.fsid.join(",");
				// 获取选中文件的dink  下载链接
				axios({
					url: "https://pan.baidu.com/rest/2.0/xpan/multimedia?method=filemetas&access_token=" +
						access_token +
						"&fsids=[" +
						Clickpath +
						"]&dlink=1",
					method: "get"
				}).then(res => {
					// 先把返回的数组放到download_url数组里面
					var download_url = res.data.list;
					// 循环下载链接   并通过aria2  下载文件
					for (var i = 0; i < this.fsid.length; i++) {
						const download =
							download_url[i].dlink + "&access_token=" + access_token;
						axios({
							url: "http://127.0.0.1:6800/jsonrpc",
							method: "post",
							crossDomain: true,
							processData: false,
							data: JSON.stringify({
								id: "",
								jsonrpc: "2.0",
								method: "aria2.addUri",
								params: [
									"token:kumao",
									[download],
									{
										"download-result": "full",
										header: "User-Agent:pan.baidu.com",
										out: download_url[i].filename
									}
								]
							}),
							headers: {
								contentType: "application/json"
							}
						}).then(res => {});
					}
					this.$Message.success("已将选中文件，添加到下载队列！");
				});
			},
			// 右键菜单下载
			handleContextMenuDownload() {
				var access_token = window.sessionStorage.getItem("access_token");
				console.log(this.ContextMenu);
				const fsid = this.ContextMenu.fs_id;
				axios({
					url: "https://pan.baidu.com/rest/2.0/xpan/multimedia?method=filemetas&access_token=" +
						access_token +
						"&fsids=[" +
						fsid +
						"]&dlink=1",
					method: "get"
				}).then(res => {
					console.log(res);

					// 先把返回的数组放到download_url数组里面
					var download_url = res.data.list[0].dlink + "&access_token=" + access_token;

					// 循环下载链接   并通过aria2  下载文件
					axios({
						url: "http://127.0.0.1:6800/jsonrpc",
						method: "post",
						crossDomain: true,
						processData: false,
						data: JSON.stringify({
							id: "",
							jsonrpc: "2.0",
							method: "aria2.addUri",
							params: [
								"token:kumao",
								[download_url],
								{
									"download-result": "full",
									header: "User-Agent:pan.baidu.com",
									out: res.data.list[0].filename
								}
							]
						}),
						headers: {
							contentType: "application/json"
						}
					}).then(res => {});
					this.$Message.success("已将选中文件，添加到下载队列！");
				});
			},
			// 右键菜单复制
			handleContextMenuCopy() {
				// 判断当前状态是复制还是粘贴
				if (this.Copy == true) {
					this.CopyFile = this.ContextMenu;
					this.$Message.success(
						"复制文件：" + this.CopyFile.server_filename + "成功！"
					);
					this.Copy = !this.Copy;
				} else {
					var path = "/" + this.path.join("/");
					var access_token = window.sessionStorage.getItem("access_token");
					var name = this.CopyFile.server_filename;
					axios({
						url: "https://pan.baidu.com/rest/2.0/xpan/file?method=filemanager&access_token="+access_token +"&opera=copy",
						method: "post",
						data: qs.stringify({
							async: 2,
							filelist: '[{"path":"/' +
								name +
								'","dest":"' +
								path +
								'","newname":"' +
								name +
								'","ondup":"overwrite"}]'
						})
					}).then(res => {
						console.log(res);
						this.$Message.success(
							"粘贴文件：" + this.CopyFile.server_filename + "成功！"
						);
						// 刷新页面
						this.Refresh();
					});
					this.Copy = !this.Copy;
				}
			},
			// 右键菜单删除
			handleContextMenuDelete(){
				this.$Modal.confirm({
					title: "温馨提示",
					content: "<p>是否需要删除该文件？</p>",
					onOk: () => {
						console.log(this.ContextMenu)
							var access_token = window.sessionStorage.getItem("access_token");
							axios({
								url: "https://pan.baidu.com/rest/2.0/xpan/file?method=filemanager&access_token=" +
									access_token +
									"&opera=delete",
								method: "post",
								data: qs.stringify({
									async: "1",
									filelist: '["' + this.ContextMenu.path + '"]'
								})
							}).then(res => {
								console.log(res);
								this.Refresh();
								this.$Message.success('删除：'+this.ContextMenu.server_filename +'成功！');
							});

					},
					onCancel: () => {
						this.$Message.info("已经取消删除。");
					}
				});






			}
		}
	};
</script>

<style>
	.ul-li {
		float: left;
		text-align: center;
		list-style: none;
		width: 100px;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		transition: .5s;
		margin: 5px;
	}

	.ul-li:hover {
		background-color: #e5f3ff;
		transform: translateY(-5px);
	}



	#disk ul ul li {
		height: 25px;
	}

	#div {
		width: 100px;
		height: 110px;
		padding: 5px;
		text-align: center;
		overflow: hidden;
		text-overflow: ellipsis;
		transition: .5s;

	}

	#div:hover {
		transform: translateY(-5px);
		background: #ddf5ff;
	}

	#div h5 {
		margin: 5px auto 0;
		text-align: center;
		width: 90%;
		overflow: hidden;
		text-overflow:ellipsis;
		white-space: nowrap;
	}
</style>
